#!/usr/bin/env python3
import cmd
import datetime
import os
import signal
import sys
import readline
import threading
import time
import glob
import json
import requests
from pathlib import Path
from typing import Callable, Optional
from auth import AuthManager
from commands import BaiduPanCommands
from config import ConfigManager
from download import DownloadManager
from help import HelpManager
from complete import Completer
from progress import ProgressSpinner, ProgressBar
from common import  format_size, format_timestamp
from common import ( # type: ignore
    CONFIG_DIR, SESSION_FILE, SESSION_EXPIRY_DAYS, COMMAND_LIST,
    DEFAULT_REMOTE_CWD, DEFAULT_DEBUG_MODE, ERROR_MESSAGES,
    SUCCESS_MESSAGES, INFO_MESSAGES, SYMBOLS
)

# 全局中断标志
interrupt_flag = False

class BaiduPanSFTP(cmd.Cmd):
    """百度网盘SFTP风格命令行工具"""
    
    intro = "\n🌐 百度网盘SFTP命令行工具 pansftp v0.5.1\n  输入 'help' 获取帮助\n"
    prompt = "baidupan> " 

    def __init__(self, non_interactive=False):
        super().__init__()
        self.debug_mode = False  # 调试模式默认关闭
        self._has_unsaved_changes = False # 未保存的修改
        self.config = ConfigManager()
        self.auth = AuthManager()
        self.access_token = self.auth.get_access_token()
        self.commands = BaiduPanCommands(self.access_token, self.debug_mode) if self.access_token else None
        self.download_manager = DownloadManager(self.commands)

        # 初始化当前工作目录
        self.remote_cwd = "/"
        self.local_cwd = os.getcwd()
        self.session_file = os.path.expanduser("~/.baidupan_session")
        self.session_expiry_days = 7  # 会话过期天数
        self.interrupt_flag = False   # 中断标志
        
        # 设置信号处理
        # 注意：暂不开启信号机制
        # self._setup_signal_handlers()

        # 非交互式模式标志
        self.non_interactive = non_interactive
        # 遇到错误是否停止执行的标志
        self.stop_on_error = True        
        # 命令执行历史记录
        self.command_history = []
        self.successful_commands = 0
        self.failed_commands = 0

        # 如果是非交互模式，跳过一些初始化
        if self.non_interactive:
            return

        # 初始化补全器
        self.completer = Completer(self)
        
        # 设置readline自动补全
        readline.set_completer(self.completer.complete)
        readline.parse_and_bind('tab: complete')
        readline.set_completer_delims(' \t\n')

        # 检测并尝试恢复会话
        self._detect_and_restore_session()

    def _log_command_execution(self, command, args):
        """记录命令执行情况"""
        full_command = f"{command} {args}".strip()
        self.command_history.append({
            'command': full_command,
            'timestamp': time.time(),
            'success': True  # 将在命令执行后更新
        })
        
        if self.non_interactive:
            print(f"执行命令: {full_command}")

    def _update_command_result(self, success):
        """更新最近执行的命令的结果"""
        if self.command_history:
            self.command_history[-1]['success'] = success
            if success:
                self.successful_commands += 1
            else:
                self.failed_commands += 1

    def get_execution_stats(self):
        """获取命令执行统计信息"""
        return {
            'total': len(self.command_history),
            'successful': self.successful_commands,
            'failed': self.failed_commands,
            'success_rate': self.successful_commands / len(self.command_history) * 100 if self.command_history else 0
        }

    def show_execution_summary(self):
        """显示命令执行摘要"""
        stats = self.get_execution_stats()
        
        print("\n📊 命令执行摘要:")
        print("=" * 40)
        print(f"  总命令数: {stats['total']}")
        print(f"  成功: {stats['successful']}")
        print(f"  失败: {stats['failed']}")
        print(f"  成功率: {stats['success_rate']:.1f}%")
        
        # 显示失败的命令
        if stats['failed'] > 0:
            print("\n❌ 失败的命令:")
            for cmd in self.command_history:
                if not cmd['success']:
                    timestamp = datetime.fromtimestamp(cmd['timestamp']).strftime("%H:%M:%S")
                    print(f"  {timestamp} - {cmd['command']}")

    def _setup_signal_handlers(self):
        """设置信号处理"""
        def signal_handler(sig, frame):
            print("\n\n⚠️  接收到中断信号，操作已取消")

            # 设置全局中断标志
            global interrupt_flag
            interrupt_flag = True

            # 如果是非交互模式
            if self.non_interactive:
                return
        
            # 清空当前输入行
            if hasattr(self, '_current_line'):
                self._current_line = ""
            # 刷新输出
            sys.stdout.write("\r" + " " * 80 + "\r")
            sys.stdout.flush()
            # 显示提示符
            sys.stdout.write(self.prompt)
            sys.stdout.flush()
        
        # 注册信号处理
        signal.signal(signal.SIGINT, signal_handler)

    def _detect_and_restore_session(self):
        """检测会话文件并提示用户是否恢复"""
        if not os.path.exists(self.session_file):
            return
        
        # 检查会话是否过期
        if self._is_session_expired():
            print("检测到过期的会话文件，将创建新会话")
            os.remove(self.session_file)
            return
        
        # 显示会话信息
        session_info = self._get_session_info()
        if session_info:
            print("检测到之前的会话状态:")
            print(f"  远程目录: {session_info.get('remote_cwd', '/')}")
            print(f"  本地目录: {session_info.get('local_cwd', os.getcwd())}")
            print(f"  最后使用: {session_info.get('last_used', '未知时间')}")
            
            # 提示用户是否恢复会话
            while True:
                choice = input("是否恢复之前的会话状态? [Y/n] (默认恢复): ").strip().lower()
                if choice in ['', 'y', 'yes']:
                    if self._load_session_state():
                        print("会话状态已恢复")
                    else:
                        print("恢复会话失败，将创建新会话")
                    break
                elif choice in ['n', 'no']:
                    print("将创建新会话")
                    # 删除会话文件
                    os.remove(self.session_file)
                    break
                else:
                    print("请输入 Y 或 N")
        else:
            print("无法读取会话信息，将创建新会话")
    
    def _get_session_info(self):
        """获取会话文件的基本信息"""
        try:
            with open(self.session_file, 'r', encoding='utf-8') as f:
                session_data = json.load(f)
            
            return {
                "remote_cwd": session_data.get("remote_cwd", "/"),
                "local_cwd": session_data.get("local_cwd", os.getcwd()),
                "last_used": session_data.get("last_used", "未知时间")
            }
        except:
            return None
    
    def _is_session_expired(self):
        """检查会话是否过期"""
        try:
            # 获取文件修改时间
            mod_time = os.path.getmtime(self.session_file)
            mod_date = datetime.datetime.fromtimestamp(mod_time)
            
            # 计算时间差
            now = datetime.datetime.now()
            delta = now - mod_date
            
            # 检查是否过期
            return delta.days > self.session_expiry_days
        except:
            return True  # 如果无法获取时间，视为过期
    
    def _save_session_state(self):
        """保存会话状态到文件"""
        session_data = {
            "remote_cwd": self.remote_cwd,
            "local_cwd": self.local_cwd,
            "last_used": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
            # 可以添加其他需要保存的状态信息
        }
        
        try:
            # 确保目录存在
            session_dir = os.path.dirname(self.session_file)
            if not os.path.exists(session_dir):
                os.makedirs(session_dir, exist_ok=True)
            
            # 写入会话数据
            with open(self.session_file, 'w', encoding='utf-8') as f:
                json.dump(session_data, f, ensure_ascii=False, indent=2)
            
            return True
        except Exception as e:
            print(f"保存会话状态失败: {e}")
            return False
    
    def _load_session_state(self):
        """从文件加载会话状态"""
        if not os.path.exists(self.session_file):
            return False
        
        try:
            with open(self.session_file, 'r', encoding='utf-8') as f:
                session_data = json.load(f)
            
            # 恢复会话状态
            self.remote_cwd = session_data.get("remote_cwd", "/")
            self.local_cwd = session_data.get("local_cwd", os.getcwd())
            
            return True
        except Exception as e:
            print(f"加载会话状态失败: {e}")
            return False

    def _save_session_history(self):
        """保存会话状态和历史记录到文件"""
        # 尝试保存会话状态
        try:
            self._save_session_state()
        except:
            pass  # 如果保存失败，继续退出
        
        # 保存历史记录
        history_file = os.path.expanduser('~/.baidupan_history')
        if 'readline' in globals():
            readline.write_history_file(history_file)

        self._has_unsaved_changes = False

    def refresh_completion_cache(self, path=None, file_list=[]):
        """刷新补全缓存"""
        if hasattr(self, 'completer') and self.completer:
            return self.completer.refresh_remote_cache(path, file_list)
        return False

    def clear_completion_cache(self):
        """清空补全缓存"""
        if hasattr(self, 'completer') and self.completer:
            self.completer.clear_cache()
            return True
        return False

    def emptyline(self):
        """处理空行（直接按回车）"""
        # 在非交互模式下，空行不应该有任何操作
        if self.non_interactive:
            return
                
        # 默认行为是重复上一个命令，我们改为无操作
        pass
    
    def default(self, line):
        """处理未知命令"""
        # 在非交互模式下，遇到未知命令应该报错并退出
        if self.non_interactive:
            print(f"❌❌❌❌ 未知命令: {line}")
            sys.exit(1)
        
        # 对于未知命令，不执行任何操作，只是提示
        if line.strip():  # 非空行
            print(f"❌ 未知命令: {line}")
            print("输入 'help' 查看可用命令")

    def preloop(self):
        """在命令行循环开始前调用"""
        # 如果是非交互模式，跳过一些初始化
        if self.non_interactive:
            return
                
        # 初始化readline历史
        history_file = os.path.expanduser('~/.baidupan_history')
        if os.path.exists(history_file):
            readline.read_history_file(history_file)

        # 设置信号处理
        # self._setup_signal_handlers()

        # 检查是否已配置客户端信息
        client_id = self.config.get_client_id()
        client_secret = self.config.get_client_secret()
        
        if not client_id or not client_secret:
            print("⚠️  未检测到客户端配置")
            print("请先配置百度网盘开放平台的应用信息:")
            print("1. 访问 https://pan.baidu.com/union/apply")
            print("2. 创建应用并获取 client_id 和 client_secret")
            print("3. 使用以下命令配置:")
            print("   config set --client-id YOUR_CLIENT_ID --client-secret YOUR_CLIENT_SECRET")
            print("   或")
            print("   config set client_id=YOUR_CLIENT_ID client_secret=YOUR_CLIENT_SECRET")
            print("")

    def postloop(self):
        """在命令行循环结束后调用"""
        # 保存会话状态
        self._save_session_state()
        print("会话状态已保存")

        # 保存历史记录
        history_file = os.path.expanduser('~/.baidupan_history')
        if 'readline' in globals():
            readline.write_history_file(history_file)
        
        # 恢复默认信号处理
        signal.signal(signal.SIGINT, signal.SIG_DFL)
   
    def precmd(self, line):
        """在命令执行前调用"""
        # 保存当前行以便中断时恢复
        self._current_line = line
        return line

    def cmdloop(self, intro=None):
        """重写cmdloop以优雅处理中断"""
        self.preloop()
        if intro is not None:
            self.intro = intro
        if self.intro:
            print(self.intro)
            print(f"远程当前目录: {self.remote_cwd}")
            print(f"本地当前目录: {self.local_cwd}")
                    
        stop = None
        while not stop:
            try:
                # 保存当前行以便中断时恢复
                self._current_line = ""
                
                if self.cmdqueue:
                    line = self.cmdqueue.pop(0)
                else:
                    # 使用readline获取输入，这样可以更好地控制中断
                    try:
                        line = input(self.prompt)
                    except EOFError:
                        line = 'EOF'
                    except KeyboardInterrupt:
                        print("^C")
                        line = ''
                
                line = self.precmd(line)
                stop = self.onecmd(line)
                stop = self.postcmd(stop, line)
            except KeyboardInterrupt:
                print("\n⚠️  操作已取消")
                # 重置状态
                stop = False
                # 清空当前输入行
                self._current_line = ""
                # 刷新输出
                sys.stdout.write("\r" + " " * 80 + "\r")
                sys.stdout.flush()
            except Exception as e:
                print(f"\n❌❌ 错误: {e}")
                stop = False
        
        self.postloop()
        return stop

    def postcmd(self, stop, line):
        """在命令执行后调用"""
        # 如果是非交互模式，直接返回停止标志
        if self.non_interactive:
            return True
                
        if line.strip() and line not in ['quit', 'exit', 'bye']:
            history_file = os.path.expanduser('~/.baidupan_history')
            readline.write_history_file(history_file)
        return stop
    
    def default(self, line):
        """处理未知命令"""
        try:
            # 对于未知命令，不执行任何操作，只是提示
            if line.strip():  # 非空行
                print(f"❌❌ 未知命令: {line}")
                print("输入 'help' 查看可用命令")
        except KeyboardInterrupt:
            print("\n⚠️  操作已取消")
            return ""

    def _check_interrupt(self):
        """检查是否收到中断信号"""
        global interrupt_flag    
        if interrupt_flag:            
            interrupt_flag = False
            raise KeyboardInterrupt("用户中断操作")

    def _check_auth(self):
        """检查是否已认证"""
        if not self.access_token or not self.commands:
            print("❌ 请先运行 'auth' 命令进行认证")
            return False
        return True
    
    def _normalize_remote_path(self, path):
        """规范化远程路径"""
        if path.startswith('/'):
            return path
        else:
            return os.path.join(self.remote_cwd, path).replace("\\", "/")
    
    def _normalize_local_path(self, path):
        """规范化本地路径"""
        if os.path.isabs(path):
            return path
        else:
            return os.path.join(self.local_cwd, path)
    
    def _format_size(self, size):
        """格式化文件大小"""
        for unit in ['B', 'KB', 'MB', 'GB', 'TB']:
            if size < 1024.0:
                return f"{size:.1f} {unit}"
            size /= 1024.0
        return f"{size:.1f} PB"

    def _show_file_list(self, file_list, path, sort_by="time", reverse=True):
        """
        以类似SFTP风格显示文件列表，支持多种排序方式
        
        参数:
            file_list: 文件列表，每个元素是包含文件信息的字典
            path: 当前目录路径
            sort_by: 排序方式，可选 "name"（文件名）、"time"（时间）、"size"（大小）
            reverse: 是否倒序排列，默认True（倒序）
        """
        # 分离目录和文件
        dirs = [item for item in file_list if item['isdir'] == 1]
        files = [item for item in file_list if item['isdir'] == 0]
        
        # 排序函数
        def sort_key(item):
            if sort_by == "name":
                return item['server_filename'].lower()
            elif sort_by == "time":
                return item.get('server_mtime', 0)
            elif sort_by == "size":
                return item.get('size', 0)
            return item.get('server_mtime', 0)  # 默认按时间排序
        
        # 分别排序目录和文件
        dirs.sort(key=sort_key, reverse=reverse)
        files.sort(key=sort_key, reverse=reverse)
        
        # 打印目录标题
        print(f"📁 目录: {path}")
        
        # 显示排序信息
        sort_direction = "倒序" if reverse else "正序"
        sort_methods = {
            "name": "文件名",
            "time": "修改时间",
            "size": "文件大小"
        }
        print(f"📊 排序: {sort_methods.get(sort_by, '修改时间')} {sort_direction}")
        print("-" * 60)
        
        # 显示目录
        for item in dirs:
            self._print_file_item(item, is_dir=True)
        
        # 显示文件
        for item in files:
            self._print_file_item(item, is_dir=False)
        
        # 显示统计信息
        print("-" * 60)
        print(f"总计: {len(dirs)} 个目录, {len(files)} 个文件")

    def _show_file_list_simple(self, file_list, path):
        """
        以类似SFTP风格显示文件列表
        
        参数:
            file_list: 文件列表，每个元素是包含文件信息的字典
            path: 当前目录路径
        """
        # 先列出目录，再列出文件
        dirs = [item for item in file_list if item['isdir'] == 1]
        files = [item for item in file_list if item['isdir'] == 0]
        
        # 按名称排序
        dirs.sort(key=lambda x: x['server_filename'].lower())
        files.sort(key=lambda x: x['server_filename'].lower())
        
        # 打印目录标题
        print(f"📁 目录: {path}")
        print("-" * 60)
        
        # 显示目录
        for item in dirs:
            self._print_file_item(item, is_dir=True)
        
        # 显示文件
        for item in files:
            self._print_file_item(item, is_dir=False)
        
        # 显示统计信息
        print("-" * 60)
        print(f"总计: {len(dirs)} 个目录, {len(files)} 个文件")
    
    def _print_file_item(self, item, is_dir):
        """格式化并打印单个文件/目录项（高级版）"""
        # 获取文件信息
        name = item['server_filename']
        size = item.get('size', 0)
        timestamp = item.get('server_mtime', 0)
        
        # 格式化大小
        size_str = self._format_size(size, is_dir)
        
        # 格式化时间
        time_str = self._format_timestamp(timestamp)
        
        # 确定图标
        icon = "📂" if is_dir else "📄"
        
        # 添加文件类型图标（可选）
        if not is_dir:
            ext = os.path.splitext(name)[1].lower()
            if ext in ['.jpg', '.jpeg', '.png', '.gif']:
                icon = "🖼️ "
            elif ext in ['.mp4', '.avi', '.mov']:
                icon = "🎬"
            elif ext in ['.mp3', '.wav', '.flac']:
                icon = "🎵"
            elif ext in ['.pdf']:
                icon = "📕"
            elif ext in ['.doc', '.docx']:
                icon = "📝"
            elif ext in ['.xls', '.xlsx']:
                icon = "📊"
            elif ext in ['.zip', '.rar', '.7z']:
                icon = "📦"
        
        # 打印条目
        print(f"{icon} {size_str} {time_str} {name}")

    def _print_file_item_simple(self, item, is_dir):
        """格式化并打印单个文件/目录项"""
        # 获取文件信息
        name = item['server_filename']
        size = item.get('size', 0)
        timestamp = item.get('server_mtime', 0)
        
        # 格式化大小
        size_str = self._format_size(size, is_dir)
        
        # 格式化时间
        time_str = self._format_timestamp(timestamp)
        
        # 确定图标
        icon = "📂" if is_dir else "📄"
        
        # 打印条目
        print(f"{icon} {size_str} {time_str} {name}")
    
    def _format_size(self, size, is_dir=False):
        """格式化文件大小，目录固定显示为0"""
        if is_dir:
            return "d".ljust(12)  # 目录显示为'd'，左对齐占12字符
        
        # 文件大小格式化
        units = ['B', 'KB', 'MB', 'GB', 'TB']
        unit_index = 0
        size_float = float(size)
        
        while size_float >= 1024 and unit_index < len(units) - 1:
            size_float /= 1024
            unit_index += 1
        
        # 根据大小选择合适的精度
        if unit_index == 0:  # 字节
            size_str = f"{size_float:.0f} {units[unit_index]}"
        elif size_float < 10:  # 小于10，保留1位小数
            size_str = f"{size_float:.1f} {units[unit_index]}"
        else:  # 大于10，保留整数
            size_str = f"{size_float:.0f} {units[unit_index]}"
        
        return size_str.rjust(12)  # 右对齐占12字符
    
    def _format_timestamp(self, timestamp):
        """格式化时间戳为 '月 日, 年 时:分' 格式"""
        if not timestamp:
            return "未知时间".ljust(20)
        
        try:
            # 将时间戳转换为datetime对象
            dt = datetime.fromtimestamp(timestamp)
            # 格式化为 "月 日, 年 时:分"
            return dt.strftime("%b %d, %Y %H:%M").ljust(20)
        except:
            return "无效时间".ljust(20)

    def do_auth(self, arg):
        """进行认证获取访问令牌"""
        # 检查是否请求帮助
        if arg in ['-h', '--help']:
            print(HelpManager.get_auth_help())
            return
            
        self.auth.authenticate()
        self.__init__()

    def _show_config(self):
        """显示当前配置: config show"""
        try:
            # 加载配置
            config = self.config.load_config()
            
            if not config:
                print("❌❌ 未找到配置信息")
                return
                
            print("🔧🔧 当前配置:")
            
            # 处理DEFAULT段（特殊段，不会出现在sections()中）
            if config.defaults():
                print("  [DEFAULT]")
                for key, value in config.defaults().items():
                    print(f"    {key} = {value}")
            
            # 处理其他段
            for section in config.sections():
                print(f"  [{section}]")
                for key, value in config.items(section):
                    print(f"    {key} = {value}")
                    
        except Exception as e:
            print(f"❌❌ 加载配置错误: {e}")
    
    def do_config(self, arg):
        """配置客户端信息"""
        args = arg.split()
        # 检查是否请求帮助
        if '-h' in args or '--help' in args:
            print(HelpManager.get_config_help())
            return

        # 显示当前配置
        if len(args) > 0 and args[0] == 'show':
            self._show_config()
            return 

        # 检查是否请求帮助
        if len(args) > 0 and (args[0] == '-h' or args[0] == '--help'):
            print(HelpManager.get_config_help())
            return
    
        # 检查参数和提示用法
        if len(args) < 1 or args[0] != 'set':
            print("❌❌ 用法: config show")
            print("         config set --client-id <ID> --client-secret <SECRET>")
            print("         config set client_id=<ID> client_secret=<SECRET>")
            return
            
        # 解析参数
        client_id = None
        client_secret = None
        redirect_uri = 'oob'
        
        # 支持两种格式的参数：
        # 1. --client-id VALUE --client-secret VALUE
        # 2. client_id=VALUE client_secret=VALUE
        
        i = 1
        while i < len(args):
            # 处理 --key value 格式
            if args[i] == '--client-id' and i + 1 < len(args):
                client_id = args[i + 1]
                i += 2
            elif args[i] == '--client-secret' and i + 1 < len(args):
                client_secret = args[i + 1]
                i += 2
            elif args[i] == '--redirect-uri' and i + 1 < len(args):
                redirect_uri = args[i + 1]
                i += 2
            # 处理 key=value 格式
            elif '=' in args[i]:
                key, value = args[i].split('=', 1)
                if key == 'client_id':
                    client_id = value
                elif key == 'client_secret':
                    client_secret = value
                elif key == 'redirect_uri':
                    redirect_uri = value
                i += 1
            else:
                print(f"❌❌ 未知参数: {args[i]}")
                return
        
        if not client_id or not client_secret:
            print("❌❌ 需要提供客户端ID和密钥")
            return
            
        # 检查是否是示例值
        if "YOUR_" in client_id or "YOUR_" in client_secret:
            print("❌❌ 请使用真实的客户端ID和密钥，而不是示例值")
            return
            
        self.auth.configure(client_id, client_secret, redirect_uri)
        print("✅ 客户端配置已保存")

    def do_ls(self, arg):
        """列出网盘目录内容: ls [-s SORT_BY] [-r] [path]"""
        # 记录命令执行
        self._log_command_execution("ls", arg)
                
        # 默认值
        sort_by = "time"  # 默认按时间排序
        reverse = True    # 默认倒序 
        path = self.remote_cwd

        # 解析参数
        args = arg.split()

        # 检查是否请求帮助
        if '-h' in args or '--help' in args:
            print(HelpManager.get_ls_help())
            return

        i = 0
        while i < len(args):
            if args[i] == "-s" and i + 1 < len(args):
                sort_by = args[i + 1]
                i += 2
            elif args[i] == "-r":
                reverse = False  # 使用正序
                i += 1
            elif not args[i].startswith("-"):
                path = args[i]
                i += 1
            else:
                print(f"❌ 未知选项: {args[i]}")
                return

        # 规范化路径
        path = self._normalize_remote_path(path)

        # 检查认证状态
        if not self._check_auth():
            return
        
        try:
            result = self.commands.list_files(path)

            if 'list' not in result or not result['list']:
                print(f"📁 空目录: {path}")
                return
                
            # # 使用统一的方法显示文件列表
            # self._show_file_list_simple(result['list'], path)

            # 使用支持排序的方法显示文件列表
            self._show_file_list(result['list'], path, sort_by, reverse)

            # 更新执行结果
            self._update_command_result(True)               
        except Exception as e:
            # 更新执行结果
            self._update_command_result(False)            
            print(f"❌ 错误: {e}")
    
    def do_cd(self, arg):
        """更改网盘当前工作目录: cd path"""
        # 记录命令执行
        self._log_command_execution("cd", arg) 

        # 检查是否请求帮助
        if arg in ['-h', '--help']:
            print(HelpManager.get_cd_help())
            return
        
        if not self._check_auth():
            return
            
        if not arg:
            print("❌ 需要指定目录路径")
            print(f"网盘当前工作目录: {self.remote_cwd}")
            return
            
        new_path = self._normalize_remote_path(arg)
        
        # 特殊处理上级目录
        if arg == "..":
            if self.remote_cwd == "/":
                print("❌ 已经是根目录")
                return
            new_path = os.path.dirname(self.remote_cwd).replace("\\", "/")
            if new_path == "":
                new_path = "/"
        
        # 检查目录是否存在
        try:
            result = self.commands.list_files(new_path, folder=1)
            if 'list' in result:
                self.remote_cwd = new_path
                print(f"📁 网盘当前工作目录: {self.remote_cwd}")

                # 更改目录后刷新补全缓存
                # self.remote_file_cache[new_path] = result['list']
                self.refresh_completion_cache(new_path, result['list'])                
            else:
                print("❌ 网盘目录不存在或无法访问")
            # 更新执行结果
            self._update_command_result(True)        
        except Exception as e:
            # 更新执行结果
            self._update_command_result(False)            
            print(f"❌ 错误: {e}")
    
    def do_pwd(self, arg):
        """显示网盘当前工作目录: pwd"""
        # 解析参数
        args = arg.split()

        # 检查是否请求帮助
        if '-h' in args or '--help' in args:
            print(HelpManager.get_pwd_help())
            return
        
        print(f"📁 网盘当前工作目录: {self.remote_cwd}")

    def do_get(self, arg):
        """从网盘下载文件到本地: get remote_file [local_file]"""
        # 检查是否请求帮助
        args = arg.split()
        if '-h' in args or '--help' in args:
            print(HelpManager.get_get_help())
            return
        
        if not self._check_auth():
            return
            
        if not arg:
            print("❌❌ 需要指定网盘文件路径")
            return

        remote_path = self._normalize_remote_path(args[0])
        
        # 确定本地保存路径
        if len(args) > 1:
            local_path = self._normalize_local_path(args[1])
        else:
            filename = os.path.basename(remote_path)
            local_path = os.path.join(self.local_cwd, filename)
        
        # 获取文件的fsid和大小
        try:
            dir_path = os.path.dirname(remote_path)
            if dir_path == "":
                dir_path = "/"
                
            result = self.commands.list_files(dir_path)
            
            if 'list' not in result or not result['list']:
                print("❌❌ 网盘文件不存在")
                return
                
            fsid = None
            file_size = 0
            for item in result['list']:
                full_path = os.path.join(dir_path, item['server_filename']).replace("\\", "/")
                if full_path == remote_path and item['isdir'] == 0:
                    fsid = item['fs_id']
                    file_size = item.get('size', 0)
                    break
                    
            if not fsid:
                print("❌❌ 网盘文件不存在或是目录")
                return
                
            # 下载文件
            print(f"⬇⬇️  下载网盘文件: {remote_path} -> {local_path}")
            
            # 创建进度条
            progress_bar = ProgressBar(file_size, "下载进度")

            # 下载文件并显示进度
            success = self.commands.download_file_with_progress(fsid, 
                local_path,
                lambda chunk: (progress_bar.update(chunk), self._check_interrupt())
            )
            if success:
                progress_bar.finish()
                print(f"✅ 下载成功: {local_path}")
            else:
                print("\n❌❌ 文件下载失败")
                # print("\n❌❌ 下载失败，请尝试以下解决方案:")
                # print("  1. 使用 'auth' 命令重新认证")
                # print("  2. 检查网络连接是否正常")
                # print("  3. 尝试使用百度网盘官方客户端下载") 
                # 清理可能的部分下载文件
                self._cleanup_partial_downloads(local_path) 
        except KeyboardInterrupt:
            print("\n⚠️  下载已取消")
        except Exception as e:
            print(f"\n❌❌ 错误: {e}")

    def _cleanup_partial_downloads(self, local_path):
        """清理部分下载的文件"""
        import glob
        # 删除可能的部分下载文件
        part_files = glob.glob(f"{local_path}.part*")
        for part_file in [local_path] or part_file in part_files:
            try:
                os.remove(part_file)
                print(f"🗑️  已清理部分下载文件: {part_file}")
            except:
                pass
    
    def do_download(self, arg):
        """下载文件: download remote_path [local_path]"""
        if not self._check_auth():
            return
            
        # 检查是否请求帮助
        args = arg.split()
        if '-h' in args or '--help' in args:
            print(HelpManager.get_download_help())
            return

        if len(args) < 1:
            print("❌ 需要指定远程文件路径")
            return
            
        remote_path = self._normalize_remote_path(args[0])
        
        # 确定本地保存路径
        if len(args) > 1:
            local_path = self._normalize_local_path(args[1])
        else:
            filename = os.path.basename(remote_path)
            local_path = os.path.join(self.local_cwd, filename)
        
        try:
            # 检查是否可恢复下载
            if os.path.exists(local_path + ".part0"):
                confirm = input("⚠️  检测到未完成的下载，是否恢复? (y/N): ").strip().lower()
                if confirm == 'y':
                    self.download_manager.resume_download(local_path)
                    return
            
            # 开始新下载
            print(f"⬇️  开始下载: {remote_path} -> {local_path}")
            
            # 进度回调函数
            def progress_callback(downloaded, total):
                percent = (downloaded / total) * 100
                print(f"\r进度: {percent:.1f}% ({downloaded}/{total})", end='', flush=True)
            
            self.download_manager.download_file(
                remote_path=remote_path,
                local_path=local_path,
                progress_callback=progress_callback
            )
            
            print("\n✅ 下载完成")
        except Exception as e:
            print(f"\n❌ 下载失败: {e}")

    def do_put(self, arg):
        """从本地上传文件到网盘: put local_file [remote_file]"""
        # 检查是否请求帮助
        args = arg.split()
        if '-h' in args or '--help' in args:
            print(HelpManager.get_put_help())
            return
                
        if not self._check_auth():
            return
            
        if not arg:
            print("❌❌ 需要指定本地文件路径")
            return

        local_path = self._normalize_local_path(args[0])
        
        if not os.path.exists(local_path):
            print("❌❌ 本地文件不存在")
            return
            
        if os.path.isdir(local_path):
            print("❌❌ 暂不支持上传目录")
            return
            
        # 确定网盘保存路径
        if len(args) > 1:
            remote_path = self._normalize_remote_path(args[1])
        else:
            filename = os.path.basename(local_path)
            remote_path = os.path.join(self.remote_cwd, filename).replace("\\", "/")
        
        try:
            # 获取文件大小
            file_size = os.path.getsize(local_path)
            print(f"⬆⬆️  上传: {local_path} -> {remote_path}")
            
            # 创建进度条
            progress_bar = ProgressBar(file_size, "上传进度")
            
            # 上传文件并显示进度
            if self.commands.upload_file_with_progress(local_path, remote_path, progress_bar.update):
                progress_bar.finish()
                print(f"✅ 上传成功: {remote_path}")
            else:
                print("\n❌❌ 上传失败，请尝试以下解决方案:")
                print("  1. 使用 'auth' 命令重新认证")
                print("  2. 检查网络连接是否正常")
                print("  3. 尝试使用百度网盘官方客户端上传")
        except KeyboardInterrupt:
            print("\n⚠️  上传已取消")
        except Exception as e:
            print(f"\n❌❌ 错误: {e}")
        
    def do_lls(self, arg):
        """列出本地目录内容: lls [path]"""
        # 解析参数
        args = arg.split()

        # 检查是否请求帮助
        if '-h' in args or '--help' in args:
            print(HelpManager.get_lls_help())
            return
            
        path = arg if arg else self.local_cwd
        path = self._normalize_local_path(path)
        
        try:
            if not os.path.exists(path):
                print("❌ 本地目录不存在")
                return
                
            print(f"📁 本地目录: {path}")
            for item in os.listdir(path):
                full_path = os.path.join(path, item)
                if os.path.isdir(full_path):
                    print(f"📂 {item}/")
                else:
                    size = os.path.getsize(full_path)
                    size_str = self._format_size(size)
                    print(f"📄 {item} {size_str}")
                    
        except Exception as e:
            print(f"❌ 错误: {e}")
    
    def do_lcd(self, arg):
        """更改本地当前工作目录: lcd path"""
        # 解析参数
        args = arg.split()

        # 检查是否请求帮助
        if '-h' in args or '--help' in args:
            print(HelpManager.get_lcd_help())
            return
                
        if not arg:
            print("❌ 需要指定目录路径")
            print(f"本地当前工作目录: {self.local_cwd}")
            return
            
        new_path = self._normalize_local_path(arg)
        
        # 特殊处理上级目录
        if arg == "..":
            if self.local_cwd == os.path.expanduser("~"):
                print("❌ 已经是用户主目录")
                return
            new_path = os.path.dirname(self.local_cwd)
        
        if os.path.isdir(new_path):
            self.local_cwd = new_path
            print(f"📁 本地当前目录: {self.local_cwd}")
        else:
            print("❌ 目录不存在")
    
    def do_lpwd(self, arg):
        """显示本地当前工作目录: lpwd"""
        # 解析参数
        args = arg.split()

        # 检查是否请求帮助
        if '-h' in args or '--help' in args:
            print(HelpManager.get_lpwd_help())
            return        

        print(f"📁 当前本地目录: {self.local_cwd}")

    def do_lmkdir(self, arg):
        """在本地创建文件夹: lmkdir dirname"""
        # 解析参数
        args = arg.split()

        # 检查是否请求帮助
        if '-h' in args or '--help' in args:
            print(HelpManager.get_lmkdir_help())
            return

        if not arg:
            print("❌ 需要指定目录名称")
            return
            
        if arg.startswith('/'):
            dir_path = arg
        else:
            dir_path = os.path.join(self.local_cwd, arg)
        
        dir_path = os.path.expanduser(dir_path)
        
        try:
            os.makedirs(dir_path, exist_ok=True)
            print(f"✅ 本地目录创建成功: {dir_path}")
        except Exception as e:
            print(f"❌ 创建本地目录失败: {e}")
	
    def do_mkdir(self, arg):
        """创建网盘目录: mkdir dirname"""
        # 解析参数
        args = arg.split()

        # 检查是否请求帮助
        if '-h' in args or '--help' in args:
            print(HelpManager.get_mkdir_help())
            return
        
        if not self._check_auth():
            return
            
        if not arg:
            print("❌ 需要指定网盘目录名称")
            return
            
        dir_path = self._normalize_remote_path(arg)
        
        try:
            if self.commands.create_folder(dir_path):
                print(f"✅ 网盘目录创建成功: {dir_path}")
            else:
                print("❌ 网盘目录创建失败")
        except Exception as e:
            print(f"❌ 错误: {e}")
    
    def do_rm(self, arg):
        """删除网盘文件或目录: rm path"""
        # 解析参数
        args = arg.split()

        # 检查是否请求帮助
        if '-h' in args or '--help' in args:
            print(HelpManager.get_rm_help())
            return

        if not self._check_auth():
            return
            
        if not arg:
            print("❌ 需要指定文件或目录路径")
            return
            
        path = self._normalize_remote_path(arg)
        
        # 确认操作
        confirm = input(f"❓ 确定要删除网盘文件或目录 '{path}' 吗？(y/N): ")
        if confirm.lower() != 'y':
            print("🗑️ 删除操作已取消")
            return
            
        try:
            if self.commands.delete_file(path):
                print(f"✅ 删除成功: {path}")
            else:
                print("❌ 删除失败")
        except Exception as e:
            print(f"❌ 错误: {e}")
    
    def do_mv(self, arg):
        """移动/重命名网盘文件: mv source dest"""
        # 解析参数
        args = arg.split()

        # 检查是否请求帮助
        if '-h' in args or '--help' in args:
            print(HelpManager.get_mv_help())
            return
        
        if not self._check_auth():
            return
            
        if not arg:
            print("❌ 需要指定网盘源路径和目标路径")
            return
            
        args = arg.split()
        if len(args) < 2:
            print("❌ 需要指定网盘源路径和目标路径")
            return
            
        source_path = self._normalize_remote_path(args[0])
        dest_path = self._normalize_remote_path(args[1])
        
        # 如果目标路径是目录，则保留原文件名
        if dest_path.endswith('/'):
            filename = os.path.basename(source_path)
            dest_path = os.path.join(dest_path, filename).replace("\\", "/")
        
        try:
            if self.commands.move_file(source_path, os.path.dirname(dest_path), os.path.basename(dest_path)):
                print(f"✅ 移动成功: {source_path} -> {dest_path}")
            else:
                print("❌ 移动失败")
        except Exception as e:
            print(f"❌ 错误: {e}")
    
    def do_cp(self, arg):
        """复制网盘文件: cp source dest"""
        # 解析参数
        args = arg.split()

        # 检查是否请求帮助
        if '-h' in args or '--help' in args:
            print(HelpManager.get_cp_help())
            return
        
        if not self._check_auth():
            return
            
        if not arg:
            print("❌ 需要指定网盘源路径和目标路径")
            return
            
        args = arg.split()
        if len(args) < 2:
            print("❌ 需要指定网盘源路径和目标路径")
            return
            
        source_path = self._normalize_remote_path(args[0])
        dest_path = self._normalize_remote_path(args[1])
        
        # 如果目标路径是目录，则保留原文件名
        if dest_path.endswith('/'):
            filename = os.path.basename(source_path)
            dest_path = os.path.join(dest_path, filename).replace("\\", "/")
        
        try:
            if self.commands.copy_file(source_path, os.path.dirname(dest_path), os.path.basename(dest_path)):
                print(f"✅ 复制成功: {source_path} -> {dest_path}")
            else:
                print("❌ 复制失败")
        except Exception as e:
            print(f"❌ 错误: {e}")
    
    def do_search(self, arg):
        """搜索网盘文件和目录: search keyword [path]"""
        # 解析参数
        args = arg.split()

        # 检查是否请求帮助
        if '-h' in args or '--help' in args:
            print(HelpManager.get_search_help())
            return
        
        if not self._check_auth():
            return
            
        if not arg:
            print("❌ 需要指定搜索关键词")
            return

        args = arg.split()
        keyword = args[0]
        if len(args) >= 2:
            path = args[1]
        else:
            path = self.remote_cwd
            
        try:
            print(f"在网盘目录 {path} 下搜索，返回名称包含关键词 {keyword} 的目录和文件。")
            result = self.commands.search_files(keyword, path)            
            if 'list' in result and result['list']:
                print(f"🔍 网盘搜索结果: {keyword}")
                # 使用统一的方法显示文件列表
                self._show_file_list(result['list'], path)
            else:
                print(f"🔍 在网盘未找到匹配文件: {keyword}")
                
        except KeyboardInterrupt:
            print("\n⚠️  搜索已取消")
        except Exception as e:
            print(f"❌ 错误: {e}")
    
    def do_refresh(self, arg):
        """刷新访问令牌: refresh"""
        # 解析参数
        args = arg.split()

        # 检查是否请求帮助
        if '-h' in args or '--help' in args:
            print(HelpManager.get_refresh_help())
            return

        if not self._check_auth():
            return
            
        try:
            if self.auth.refresh_token():
                self.access_token = self.auth.get_access_token()
                self.commands = BaiduPanCommands(self.access_token, self.debug_mode)
                print("✅ 访问令牌刷新成功")
            else:
                print("❌ 刷新令牌失败")
        except Exception as e:
            print(f"❌ 错误: {e}")
    
    def do_logout(self, arg):
        """清除认证信息: logout [--all]"""
        # 解析参数
        args = arg.split()

        # 检查是否请求帮助
        if '-h' in args or '--help' in args:
            print(HelpManager.get_logout_help())
            return

        args = arg.split()
        clear_all = False

        # 检查是否请求帮助
        if len(args) > 0 and (args[0] == '-h' or args[0] == '--help'):
            print(HelpManager.get_logout_help())
            return
            
        if len(args) > 0 and args[0] == '--all':
            clear_all = True
        
        try:
            # 清除认证信息
            self.auth.logout()
            self.access_token = None
            self.commands = None
            
            if clear_all:
                # 清除客户端配置
                self.auth.clear_client_config()
                print("✅ 所有认证信息和客户端配置已清除")
            else:
                print("✅ 认证信息已清除（客户端配置保留）")
                
        except Exception as e:
            print(f"❌❌ 错误: {e}")

    def do_tree(self, arg):
        """显示网盘目录树: tree [path]"""
        # 解析参数
        args = arg.split()

        # 检查是否请求帮助
        if '-h' in args or '--help' in args:
            print(HelpManager.get_tree_help())
            return

        if not self._check_auth():
            return
            
        path = arg if arg else self.remote_cwd
        path = self._normalize_remote_path(path)
        
        try:
            self._print_directory_tree(path, 0)
        except KeyboardInterrupt:
            print("\n⚠️  操作已取消")
        except Exception as e:
            print(f"❌ 错误: {e}")
    
    def _print_directory_tree(self, path, depth, prefix=""):
        """递归输出目录树"""
        # 获取目录内容
        result = self.commands.list_files(path)
        
        if 'list' not in result or not result['list']:
            return
            
        items = result['list']
        # 先列出目录，再列出文件
        dirs = [item for item in items if item['isdir'] == 1]
        files = [item for item in items if item['isdir'] == 0]
        
        # 输出当前目录
        dir_name = os.path.basename(path)
        if depth == 0:
            print(f"📁 {path}")
        else:
            print(f"{prefix}├── 📁 {dir_name}")
        
        # 输出子目录
        for i, item in enumerate(dirs):
            full_path = os.path.join(path, item['server_filename']).replace("\\", "/")
            is_last = (i == len(dirs) - 1 and len(files) == 0)
            new_prefix = prefix + ("    " if depth > 0 else "") + ("│   " if not is_last else "    ")
            
            if is_last:
                print(f"{prefix}└── 📁 {item['server_filename']}")
                self._print_directory_tree(full_path, depth + 1, new_prefix)
            else:
                print(f"{prefix}├── 📁 {item['server_filename']}")
                self._print_directory_tree(full_path, depth + 1, new_prefix)
        
        # 输出文件
        for i, item in enumerate(files):
            is_last = (i == len(files) - 1)
            size = self._format_size(item.get('size', 0))
            
            if is_last:
                print(f"{prefix}└── 📄 {item['server_filename']} {size}")
            else:
                print(f"{prefix}├── 📄 {item['server_filename']} {size}")
    
    def do_meta(self, arg):
        """显示网盘文件详细信息: meta path"""
        # 解析参数
        args = arg.split()

        # 检查是否请求帮助
        if '-h' in args or '--help' in args:
            print(HelpManager.get_meta_help())
            return

        if not self._check_auth():
            return
            
        if not arg:
            print("❌ 需要指定网盘文件路径")
            return
            
        path = self._normalize_remote_path(arg)
        
        try:
            # 获取文件元数据
            dir_path = os.path.dirname(path)
            if dir_path == "":
                dir_path = "/"
                
            result = self.commands.list_files(dir_path)
            
            if 'list' not in result or not result['list']:
                print("❌ 网盘文件不存在")
                return
                
            file_info = None
            for item in result['list']:
                full_path = os.path.join(dir_path, item['server_filename']).replace("\\", "/")
                if full_path == path:
                    file_info = item
                    break
                    
            if not file_info:
                print("❌ 网盘文件不存在")
                return
                
            # 打印元数据
            print(f"📄 网盘文件详细信息: {path}")
            print(f"  文件名: {file_info.get('server_filename')}")
            print(f"  文件ID: {file_info.get('fs_id')}")
            print(f"  大小: {self._format_size(file_info.get('size', 0))}")
            print(f"  是否目录: {'是' if file_info.get('isdir') == 1 else '否'}")
            print(f"  MD5: {file_info.get('md5', '未知')}")
            print(f"  创建时间: {self._format_timestamp(file_info.get('server_ctime'))}")
            print(f"  修改时间: {self._format_timestamp(file_info.get('server_mtime'))}")
            print(f"  本地创建时间: {self._format_timestamp(file_info.get('local_ctime'))}")
            print(f"  本地修改时间: {self._format_timestamp(file_info.get('local_mtime'))}")
            
        except Exception as e:
            print(f"❌ 错误: {e}")
    
    def do_rename(self, arg):
        """重命名网盘文件/目录: rename path newname"""
        # 解析参数
        args = arg.split()

        # 检查是否请求帮助
        if '-h' in args or '--help' in args:
            print(HelpManager.get_rename_help())
            return

        if not self._check_auth():
            return
            
        args = arg.split()
        if len(args) < 2:
            print("❌ 用法: rename <路径> <新名称>")
            return
            
        path = self._normalize_remote_path(args[0])
        new_name = args[1]
        
        try:
            # 获取文件所在目录
            dir_path = os.path.dirname(path)
            if dir_path == "":
                dir_path = "/"
                
            # 重命名文件
            if self.commands.rename_file(path, new_name):
                new_path = os.path.join(dir_path, new_name).replace("\\", "/")
                print(f"✅ 重命名成功: {path} -> {new_path}")
            else:
                print("❌ 重命名失败")
        except Exception as e:
            print(f"❌ 错误: {e}")
    
    def do_status(self, arg):
        """显示当前工具状态: status"""
        # 解析参数
        args = arg.split()

        # 检查是否请求帮助
        if '-h' in args or '--help' in args:
            print(HelpManager.get_status_help())
            return

        # 认证状态
        if self.access_token:
            auth_status = "✅ 已认证"
            # 获取令牌过期时间
            expires_at = self.auth.get_token_expiration()
            if expires_at:
                from datetime import datetime
                expires_str = datetime.fromtimestamp(expires_at).strftime("%Y-%m-%d %H:%M:%S")
                auth_status += f" (过期时间: {expires_str})"
        else:
            auth_status = "❌ 未认证"
        
        # 远程目录
        remote_dir = self.remote_cwd
        
        # 本地目录
        local_dir = self.local_cwd
        
        # 打印状态
        print("📊 当前工具状态:")
        print(f"  认证状态: {auth_status}")
        print(f"  远程目录: {remote_dir}")
        print(f"  本地目录: {local_dir}")
        
        # 如果已认证，显示网盘空间使用情况
        if self.access_token:
            try:
                result = self.commands.quota()
                
                if 'total' in result and 'used' in result:
                    total = result['total']
                    used = result['used']
                    free = total - used
                    
                    # print(f"  网盘空间: {self._format_size(used)}/{self._format_size(total)}")
                    print(f"  网盘空间: {self._format_size(total)}")
                    print(f"  已用空间: {self._format_size(used)}")
                    print(f"  剩余空间: {self._format_size(free)}")
                    print(f"  使用率: {used/total*100:.2f}%")
            except Exception as e:
                print(f"  网盘空间信息获取失败: {e}")

    def _format_timestamp(self, timestamp):
        """格式化时间戳"""
        if not timestamp:
            return "未知"
            
        from datetime import datetime
        try:
            return datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")
        except:
            return "无效时间戳"

    def do_quota(self, arg):
        """查看网盘容量信息: quota"""
        # 解析参数
        args = arg.split()

        # 检查是否请求帮助
        if '-h' in args or '--help' in args:
            print(HelpManager.get_quota_help())
            return

        if not self._check_auth():
            return
            
        try:
            result = self.commands.quota()
            
            if 'total' in result and 'used' in result:
                total = result['total']
                used = result['used']
                free = total - used
                
                print(f"💾 网盘空间使用情况:")
                print(f"  总空间: {self._format_size(total)}")
                print(f"  已使用: {self._format_size(used)}")
                print(f"  剩余空间: {self._format_size(free)}")
                print(f"  使用率: {used/total*100:.2f}%")
                print(f"  7天内到期: {result['expire']}")

            else:
                print("❌ 无法获取配额信息")
                
        except Exception as e:
            print(f"❌ 错误: {e}")
    
    def do_userinfo(self, arg):
        """获取用户信息: userinfo"""
        # 解析参数
        args = arg.split()

        # 检查是否请求帮助
        if '-h' in args or '--help' in args:
            print(HelpManager.get_userinfo_help())
            return

        if not self._check_auth():
            return
            
        try:
            result = self.commands.user_info()
            
            if 'baidu_name' in result:
                print("👤 用户信息:")
                print(f"  用户昵称: {result.get('baidu_name')}")
                print(f"  用户账号 {result.get('netdisk_name')}")
                print(f"  网盘ID: {result.get('uk')}")
                print(f"  头像: {result.get('avatar_url')}")
                print(f"  会员类型: {result.get('vip_type', '普通用户')}")
            else:
                print("❌ 无法获取用户信息")
                
        except Exception as e:
            print(f"❌ 错误: {e}")

    def do_perf(self, arg):
        """显示性能统计: perf"""
        # 解析参数
        args = arg.split()

        # 检查是否请求帮助
        if '-h' in args or '--help' in args:
            print(HelpManager.get_perf_help())
            return

        if not self._check_auth():
            return
            
        stats = self.commands.get_performance_stats()
        
        print("📊 性能统计:")
        print(f"  总请求数: {stats['total_requests']}")
        print(f"  失败请求: {stats['failed_requests']}")
        print(f"  总请求时间: {stats['total_time']:.2f}秒")
        print(f"  平均响应时间: {stats['avg_response_time']:.3f}秒")
        print(f"  最后请求时间: {time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(stats['last_request_time']))}")
        print(f"  最后请求耗时: {(stats['last_request_cost']):.3f}秒")

    def do_debug(self, arg):
        """设置调试模式: debug [on|off]"""
        # 解析参数
        args = arg.split()

        # 检查是否请求帮助
        if '-h' in args or '--help' in args:
            print(HelpManager.get_debug_help())
            return
        
        args = arg.split()
        if not args:
            # 显示当前调试状态
            status = "开启" if self.debug_mode else "关闭"
            print(f"🔧 调试模式: {status}")
            return
            
        if args[0] == "on":
            self.debug_mode = True
            if self.commands:
                self.commands.debug_mode = True
            print("✅ 调试模式已开启")
        elif args[0] == "off":
            self.debug_mode = False
            if self.commands:
                self.commands.debug_mode = False
            print("✅ 调试模式已关闭")
        else:
            print("❌ 用法: debug [on|off]")

    def do_reset_session(self, arg):
        """重置会话状态: reset_session"""
        # 删除会话文件
        if os.path.exists(self.session_file):
            os.remove(self.session_file)
            print("会话状态已重置")
        
        # 重置目录
        self.remote_cwd = "/"
        self.local_cwd = os.getcwd()
        print(f"远程目录重置为: {self.remote_cwd}")
        print(f"本地目录重置为: {self.local_cwd}")
    
    def do_session_info(self, arg):
        """显示当前会话信息: session_info"""
        if os.path.exists(self.session_file):
            try:
                mod_time = os.path.getmtime(self.session_file)
                mod_date = datetime.datetime.fromtimestamp(mod_time)
                print(f"会话文件: {self.session_file}")
                print(f"创建时间: {mod_date.strftime('%Y-%m-%d %H:%M:%S')}")
                
                with open(self.session_file, 'r', encoding='utf-8') as f:
                    session_data = json.load(f)
                
                print(f"远程目录: {session_data.get('remote_cwd', '/')}")
                print(f"本地目录: {session_data.get('local_cwd', os.getcwd())}")
                print(f"最后使用: {session_data.get('last_used', '未知时间')}")
            except Exception as e:
                print(f"读取会话信息失败: {e}")
        else:
            print("没有找到会话文件")

    def do_quit(self, arg):
        """退出程序: quit"""
        try:        
            # 解析参数
            args = arg.split()

            # 检查是否请求帮助
            if '-h' in args or '--help' in args:
                print(HelpManager.get_quit_help())
                return

            force = '-f' in args or '--force' in args
            save = '-s' in args or '--save' in args
            
            # 执行退出逻辑
            if save:
                self._save_session_history()
            
            if not force:
                # 检查是否有未完成的操作
                if self._has_unsaved_changes:
                    try:
                        confirm = input("⚠️  有未保存的更改，确定要退出吗？(y/N): ")
                        if confirm.lower() != 'y':
                            print("退出已取消")
                            return
                    except KeyboardInterrupt:
                        print("\n⚠️  退出已取消")
                        return
            
            return True
        except KeyboardInterrupt:
            print("\n⚠️  退出已取消")
            return False    
        finally:
            print("👋👋 再见！")

    def do_exit(self, arg):
        """退出程序: exit"""
        return self.do_quit(arg)
    
    def do_bye(self, arg):
        """退出程序: bye"""
        return self.do_quit(arg)

    def do_help(self, arg):
        """显示帮助信息: help"""
        if not arg:
            # 显示可用命令列表
            print(HelpManager.get_general_help())
            return

        # 显示特定命令的帮助
        help_text = HelpManager.get_command_help(arg)
        print(help_text)

def main():
    # 确保配置目录存在
    config_dir = Path.home() / ".baidupan"
    if not config_dir.exists():
        config_dir.mkdir(parents=True, exist_ok=True)
    
    # 启动SFTP命令行
    sftp = BaiduPanSFTP()
    sftp.cmdloop()

if __name__ == "__main__":
    main()
